#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <stdbool.h>
#include <signal.h>
#include<errno.h>
#include <sys/stat.h>
#include <fcntl.h>

#define ERRLOG(errmsg) do{\
                            printf("file:%s,func:%s,line:%d\n",__FILE__,__func__,__LINE__);\
                            perror(errmsg);\
                            exit(-1);\
                        }while(0);

int main(int argc, char const *argv[])
{
    if(mkfifo("mkfifo1",0644)==-1){
        if(errno!=17){
            ERRLOG("mkfifo1 error");
        }else {
            printf("mkfifo1 exist\n");
        }
    }

    if(mkfifo("mkfifo2",0644)==-1){
        if(errno!=17){
            ERRLOG("mkfifo2 error");
        }else {
            printf("mkfifo2 exist\n");
        }
    }

    int fd1;
    if((fd1=open("mkfifo1",O_RDWR))==-1){
        ERRLOG("open1 error");
    }

    int fd2;
    if((fd2=open("mkfifo2",O_RDWR))==-1){
        ERRLOG("open2 error");
    }
    char buf[20]={0};
    pid_t pid=fork();
    if(pid<0){
        ERRLOG("fork error");
    }else if(pid>0){
        while(1){
            fgets(buf,sizeof(buf),stdin);
            buf[strlen(buf)-1]='\0';
            if(write(fd2,buf,sizeof(buf))==-1){
                ERRLOG("write error");
            }
            memset(buf, 0, sizeof(buf));
        }
    }else {
        while(1){
            if(read(fd1,buf,sizeof(buf))==-1){
                ERRLOG("read error");
            }
            printf("buf=%s\n");
            memset(buf,0,sizeof(buf));
        }
    }
    return 0;
}
